import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/screenutil.dart';
import 'package:shop/config/config.dart';
import 'package:shop/http/HttpUtil.dart';
import 'package:shop/route/my_route.dart';
import 'package:shop/shop/merchant/GoodsInfoEdit.dart';
import 'package:shop/shop/merchant/GoodsTypePage.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:shared_preferences/shared_preferences.dart';

class AddGoodType extends StatefulWidget {
  bool isEdit;      //true:修改 false:添加
  String typeName;  //类型名称
  String typeId;    //类型ID
  String mTypeId;   //商户类型ID
  AddGoodType({Key key, this.title,this.isEdit,this.typeName,this.mTypeId,this.typeId}) : super(key: key);

  final String title;

  @override
  _AddGoodType createState() => _AddGoodType(isEdit,typeName,mTypeId,typeId);
}

class _AddGoodType extends State<AddGoodType> with SingleTickerProviderStateMixin {
  TextEditingController _typeNameController; // 文本框控制器
  TextEditingController _mTypeNameController; // 文本框控制器
  String merchantID="";  //商户ID
  String typeName;       //类型名称
  String typeId;         //类型ID
  String mTypeId;        //商户类型ID
  String mTypeName;      //商户类型名称
  List<DropdownMenuItem> mTypeNameList =[];//商户类型名称集合
  bool isEdit = true;    //修改还是添加（1：修改类型  0：新增类型）
  SharedPreferences prefs;

  // 构造方法
  _AddGoodType(isEdit,typeName,mTypeId,typeId){
    this.isEdit=isEdit;
    this.typeName=typeName;
    this.mTypeId=mTypeId;
    this.typeId=typeId;
    _typeNameController = new TextEditingController(text: typeName);
    _getMercantType();
  }

  _getMercantType() async {
    prefs = await SharedPreferences.getInstance();
    merchantID = prefs.getString("merchantID");
    //查询商户类型
    var res;
    if(isEdit){//修改
      res = await HttpUtil().get("/waimai/mGoodsType/getMerchantType?mId="+merchantID+"&mTypeId="+mTypeId+"&isExit=1");
      if(res['code']==200){
        mTypeName =  res['msg'];//商户类型名称
        _mTypeNameController = new TextEditingController(text: mTypeName);
      }
    }else{     //新增
      res = await HttpUtil().get("/waimai/mGoodsType/getMerchantType?mId="+merchantID+"&isExit=0");
      if(res['code']==200){
        mTypeName =  res['data'][0];//商户类型名称
        for(int i=0;i<res['data'].length;i++){
          mTypeNameList.add(DropdownMenuItem(child: Text(res['data'][i]),value: res['data'][i],),);//商户类型名称集合
        }
      }
    }
    setState(() {});
  }
  // @override
  // void initState(){
  //   super.initState();
  //   // 初始化文本框
  //   TypeNameController.text=name;
  //   if(name==null)  // 如果name为空，表示新增
  //     isEdit=false;
  // }
  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context , width: 464 , height: 820) ;
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text("编辑分类"),
        actions: [
          IconButton(icon: Icon(Icons.save), onPressed: () async {
            var url = "waimai/mGoodsType/updateMGoodsType"; // 修改地址
            if(isEdit==false){
              url="waimai/mGoodsType/addMGoodsType";  // 新增地址
            }
            var map = new Map<String,dynamic>();
            map['mid']=merchantID;//商户ID
            map['id']=typeId;//商品类型ID
            map['name']=_typeNameController.text.trim();  // 商品分类名称
            map['mtype']=mTypeName; // 商户类型
            map['status']=1;//类型状态
            print(map);
            var x = await HttpUtil().post(url,map);
            var res = json.decode(x.toString());
            if(res['code']==200){
              if(isEdit){
                Fluttertoast.showToast(msg: "编辑成功");
              }else{
                Fluttertoast.showToast(msg: "添加成功");
              }
              Future.delayed(Duration(seconds: 1), () {
                MyRoute.replace(GoodsTypePage());
              });
            }else{
              Fluttertoast.showToast(
                  msg: res['msg']
              );
            }
          })
        ],
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            Container(
              padding: EdgeInsets.fromLTRB(10, 0, 0, 0),
              child: isEdit ?  Row(
                children: [
                  Row(children: [Text("*",style: TextStyle(color: Colors.red),),Text("商户类型"),SizedBox(width: 5,),],),
                  SizedBox(width: 30,),
                  Expanded(child: TextFormField(
                    controller: _mTypeNameController,
                    decoration: InputDecoration(
                      enabled: false//文本框不可编辑
                    ),
                  ))
                ],
              ) : Row(
                children: [
                  Row(children: [Text("*",style: TextStyle(color: Colors.red),),Text("商户类型"),SizedBox(width: 5,),],),
                  SizedBox(width: 30,),
                  Expanded(
                    child: DropdownButton(
                      hint: Text("请选择商户类型"),
                      value: mTypeName,
                      items: mTypeNameList,
                      isExpanded: true,
                      onChanged: (value) {
                        setState(() {
                          mTypeName=value;
                        });
                      }
                    )
                  )
                ],
              ),
            ),
            Container(
              padding: EdgeInsets.fromLTRB(10, 0, 0, 0),
              child: Row(
                children: [
                  Row(children: [Text("*",style: TextStyle(color: Colors.red),),Text("分类名称"),SizedBox(width: 5,),],),
                  SizedBox(width: 30,),
                  Expanded(child: TextFormField(
                    controller: _typeNameController,
                    decoration: InputDecoration(
                      hintText: "编辑分类名称",
                      hintStyle: TextStyle(fontSize: 14)
                    ),
                  ))
                ],
              ),
            )
          ],
        ),
      ),
    );
  }
}